package com.cybertron.lockdown.spider;

import com.cybertron.lockdown.spider.handler.HandleRequest;
import com.cybertron.lockdown.spider.util.PropertiesUtil;
import org.apache.log4j.Appender;
import org.apache.log4j.WriterAppender;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.PipedReader;
import java.io.PipedWriter;
import java.io.Writer;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

/**
 * Created by xiezhouyan on 15-1-10.
 */
public class SpiderBootstrap {

    private static Logger logger = LoggerFactory.getLogger(SpiderBootstrap.class);

    private static final SpiderRunner RUNNER = SpiderRunner.create();

    private static final Integer PORT = PropertiesUtil.getInt("port");

    private static Scanner LOGSCANNER;

    public static void initScanner() {
        try {
            org.apache.log4j.Logger root = org.apache.log4j.Logger.getRootLogger();
            Appender appender = root.getAppender("stdout");
            PipedReader reader = new PipedReader();
            Writer writer = new PipedWriter(reader);
            ((WriterAppender) appender).setWriter(writer);
            LOGSCANNER = new Scanner(reader);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        RUNNER.run();
        ServerSocket serverSocket;
        Socket socket = null;
        HandleRequest request = null;
        try {
            serverSocket = new ServerSocket(PORT);

            logger.info("listening {}, wait for client ", PORT);
            initScanner();
            while (true) {
                socket = serverSocket.accept();
                if (request != null && request.isAlive()) {
                    socket.close();
                } else {
                    request = new HandleRequest(RUNNER, LOGSCANNER, socket);
                    request.setName("handle-request-thread");
                    request.setDaemon(true);
                    request.start();
                }
            }
        } catch (IOException e) {
            logger.error("accept client error", e);
        } finally {
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}